package com.dubbo.web.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
import java.util.zip.CRC32;

/**   
* @Title: ConsistentHash.java 
* @Package com.dubbo.web.util 
* @Description: TODO(用一句话描述该文件做什么) 
* @author liusongqing 
* @Company www.viewhigh.com
* @date 2016年8月30日 下午4:36:14 
* @version V1.0   
*/
public class ConsistentHash<T> {

    private int num = 1;

    private final Vector<T> circle = new Vector<T>();

    public static void main(String args[]) {
        List<String> list = new ArrayList<String>();
        String node1 = "node1";
        String node2 = "node2";
        list.add(node1);
        list.add(node2);
        ConsistentHash<String> ch = new ConsistentHash<String>(list);
        // System.out.println((int) (Math.abs(ch.hashcode(2+"")) % list.size()));
        System.out.println(ch.get(2));
    }

    public ConsistentHash(Collection<T> nodes) {
        num = nodes.size();
        num = num > 0 ? num : 1;
        circle.addAll(nodes);
    }

    public static long hashcode(String input) {
        CRC32 crc32 = new CRC32();
        crc32.update(input.getBytes());
        return crc32.getValue();
    }

    public T get(Object key) {
        if (circle.isEmpty()) {
            return null;
        }
        return circle.get((int) (Math.abs(hashcode(key.toString())) % num));
    }
}

